package com.xhs.service.impl;

import com.xhs.service.ResetRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;

/**
 * @desc: 按月重置规则
 * @projectName: auto-number
 * @author: xhs
 * @date: 2025-03-12 周三 13:46
 * @version: JDK 21
 */
@Slf4j
@Service("monthly")
public class MonthlyResetRule implements ResetRule {

    @Override
    public String getKeySuffix(LocalDateTime currentTime) {
        return currentTime.format(DateTimeFormatter.ofPattern("yyyyMM"));
    }

    @Override
    public boolean isExpired(String key, LocalDateTime currentTime) {
        String[] parts = key.split(":");
        if (parts.length < 2) {
            // Key 格式错误，强制重置
            return true;
        }
        // 如果 Key 的后缀与当前时间的后缀不一致，则需要重置
        String currentSuffix = getKeySuffix(currentTime);
        return !parts[parts.length - 1].equals(currentSuffix);
    }

    /**
     * 获取过期时间 秒
     *
     * @return long
     */
    @Override
    public long expirationTime() {
        // 动态计算
        LocalDateTime now = LocalDateTime.now();
        LocalDate endOfMonth = now.toLocalDate().with(TemporalAdjusters.lastDayOfMonth());
        LocalDateTime endOfMonthTime = endOfMonth.atTime(23, 59, 59);
        return Duration.between(now, endOfMonthTime).getSeconds();
    }

    /**
     * 获取前一个周期的Key后缀
     *
     * @param currentTime 当前时间
     * @return String
     */
    @Override
    public String getPreviousKeySuffix(LocalDateTime currentTime) {
        return currentTime.minusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMM"));
    }
}
